package com.ch7_6;

import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;

/**
 * Created by wangjing on 2018/7/18.
 */
@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter{
    protected void configure(HttpSecurity http) throws  Exception{
        http.authorizeRequests()
                .antMatchers("/","/login").permitAll()//设置spring Security对/和/login路径不拦截
                .anyRequest().authenticated()
                .and()
                .formLogin()
                .loginPage("/login")//设置登录页面路径
                .defaultSuccessUrl("/chat")//登录成功后转向/chat
                .permitAll()
                .and()
                .logout()
                .permitAll();
    }

    /**
     * 设置内存两个用户
     * @param auth
     * @throws Exception
     */
    protected void configure(AuthenticationManagerBuilder auth) throws Exception{
//        auth
//                .inMemoryAuthentication()
//                .withUser("heqiang").password("heqiang").roles("USER")
//                .and()
//                .withUser("wisely").password("wisely").roles("USER");

        auth
                .inMemoryAuthentication()
                .passwordEncoder(new BCryptPasswordEncoder())
                .withUser("heqiang").password(new BCryptPasswordEncoder().encode("heqiang")).roles("USER")
                .and()
                .passwordEncoder(new BCryptPasswordEncoder())
                .withUser("wisely").password(new BCryptPasswordEncoder().encode("wisely")).roles("USER");
    }

    /**
     * 不拦截静态资源
     * @param web
     * @throws Exception
     */
    public void configure(WebSecurity web) throws Exception{
        web.ignoring().antMatchers("/resources/static/**");
    }
}
